<?php

namespace app\controller\wmapi\partner;

use app\controller\wmapi\IndexController;
use app\model\WaChannel;
use Illuminate\Support\Facades;
use Illuminate\Support\Facades\Validator;
use plugin\admin\app\common\Util;
use plugin\admin\app\model\Admin;
use support\Request;
use app\model\WaAdmins;
use app\model\WaRoles;
use app\model\WaMembers;
use app\model\WaRules;
use app\model\WaDepartment;
use app\model\WaAdminRoles;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Cache;
use Tinywan\Validate\Validate;

class ChannelController extends Validate
{
    /**
     * 客户管理 -列表-分页
     * @param Request $request
     * @return mixed
     */
    public function channelList(Request $request)
    {
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        $fields = ['*'];
        $condition = [];
        $between = [];
        if ($param['name']) {
            $condition [] = ['name', 'like', '%' . $param['name'] . '%'];
        }

        if ($param['phone']) {
            $condition [] = ['phone', '=', $param['phone']];
        }

        if ($param['email']) {
            $condition [] = ['email', '=', $param['email']];
        }

        if ($param['country']) {
            $condition [] = ['country', 'like', '%' . $param['country'] . '%'];
            $condition [] = ['area', 'like', '%' . $param['country'] . '%'];
        }

        if ($param['start_time'] && $param['end_time']) {
            $between [] = [$param['start_time'], $param['end_time']];
        }
        $next_epartment_members = IndexController::nextDepartmentMembers($adminId);
        $whereIn = $next_epartment_members;
        $page = page($param['page']);
        $pageNum = pageNum($param['pageNum']);
        $rule = WaChannel::list($page, $pageNum, $whereIn,$fields, $condition, $between);

        return IndexController::successed($rule, '渠道列表');
    }

    /**
     * 客户管理 -列表-不分页
     * @param Request $request
     * @return mixed
     */
    public function channelAll(Request $request)
    {
//        process($request);
        $param = $request->all();
        $fields = ['*'];
        $condition = [];
        $rule = WaChannel::all($fields, $condition);
        return IndexController::successed($rule, '渠道列表');
    }

    /**
     * 客户-创建
     * @param Request $request
     * @return \support\Response
     */
    public function channelCreate(Request $request)
    {
        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        /**
         * 验证规则
         */
        $rule = [
            'name' => 'require|max:50', // 用户名
            'phone' => 'require', //
            'maintainer_admin_id' => 'require', //
            'term_id' => 'require', //
        ];


        $data = [
            'name' => $param['name'], // 客户名字/企业名称
            'country' => $param['country'],
            'area' => $param['area'],
            'area_code' => $param['area_code'],
            'address' => $param['address'],
            'phone' => $param['phone'],
            'email' => $param['email'],
            'passport_number' => $param['passport_number'],// 护照号码
            'maintainer_admin_id' => $param['maintainer_admin_id'],// 维护人(admin_id)
            'business_license_number' => $param['business_license_number'],// 营业执照号
            'tax_registration_number' => $param['tax_registration_number'],// 税务登记号
            'remark' => $param['remark'],// 备注
            'type' => $param['type'],// 1个人 2 企业
            'linkman' => $param['linkman'],
            'created_at' => dateTime(),
            'created_id' => $adminId->id, // 创建人
            'status' => 0,
        ];

        $validate = \Tinywan\Validate\Facade\Validate::rule($rule);
        if (!$validate->check($param)) {
            return IndexController::errored($validate->getError());
        } else {
            $where = ['phone' => $param['phone']];
            $find = WaChannel::find($where);
            $find = json_decode($find);
            if ($find){
                if (property_exists($find, 'id')) {
                    return IndexController::errored('', '渠道创建失败,渠道电话已存在');
                }
            }
            \support\Db::beginTransaction();
            try {
                $res = WaChannel::created($data);
                \support\Db::commit();
                return IndexController::successed($res, '渠道创建成功');
            } catch (\Throwable $exception) {

                IndexController::logError('channelCreate', $param, $adminId, $exception);
                \support\Db::rollBack();
                return IndexController::errored($exception, '渠道创建失败');
            }

        }

    }

    /**
     * 客户-更新
     * @param Request $request
     * @return \support\Response
     */
    public function channelEdit(Request $request)
    {
        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        /**
         * 验证规则
         */
        $rule = [
            'name' => 'require|max:50', // 用户名
            'phone' => 'require', //
            'maintainer_admin_id' => 'require', //
            'term_id' => 'require', //
        ];


        $data = [
            'name' => $param['name'], // 客户名字/企业名称
            'country' => $param['country'],
            'area' => $param['area'],
            'area_code' => $param['area_code'],
            'address' => $param['address'],
            'phone' => $param['phone'],
            'email' => $param['email'],
            'passport_number' => $param['passport_number'],// 护照号码
            'maintainer_admin_id' => $param['maintainer_admin_id'],// 维护人(admin_id)
            'business_license_number' => $param['business_license_number'],// 营业执照号
            'type' => $param['type'],// 1个人 2 企业
            'linkman' => $param['linkman'],
            'tax_registration_number' => $param['tax_registration_number'],// 税务登记号
            'remark' => $param['remark'],// 备注
            'updated_at' => dateTime(),
        ];

        if ($param['status'] || $param['status'] == 0) {
            $data['status'] = $param['status']; // 0默认  1正常 2 禁用 4 删除
        }
        if ($param['term_id']){ $data['term_id'] = $param['term_id']; }


        $validate = \Tinywan\Validate\Facade\Validate::rule($rule);
        if (!$validate->check($param)) {
            return IndexController::errored($validate->getError());
        } else {
            $where = ['phone' => $param['phone']];
            $find = WaChannel::find($where);
            $find = json_decode($find);
            if ($find) {
                if ($param['channel_id'] != $find->id) {
                    return IndexController::errored('', '渠道更新失败,渠道电话已存在');
                }
            }
            $condition = [];
            $condition [] = ['id', '=', intval($param['channel_id'])];
            \support\Db::beginTransaction();
            try {
                $res = WaChannel::updated($condition, $data);
                \support\Db::commit();
                return IndexController::successed('', '渠道更新成功');
            } catch (\Throwable $exception) {
                IndexController::logError('channelEdit', $param, $adminId, $exception);
                \support\Db::rollBack();
                return IndexController::errored($exception, '渠道更新失败');
            }

        }
    }

    /**
     * 客户-删除
     * @param Request $request
     * @return \support\Response
     */
    public function channelDel(Request $request)
    {
        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        $condition = [];
        $condition []= ['id', '=', $param['channel_id']];

        $data = [
            'status' => 4,
            'updated_at' => dateTime(),
        ];
        \support\Db::beginTransaction();
        try {
            $rule = WaChannel::updated($condition,$data);
            \support\Db::commit();
            return IndexController::successed('', '渠道-删除成功');
        } catch (\Throwable $exception) {

            IndexController::logError('channelDel', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '渠道-删除成功');
        }

    }

    /**
     * 管理员-详情
     * @param Request $request
     * @return \support\Response
     */
    public function channelDetail(Request $request)
    {
        process($request);
        $param = $request->all();
        $condition = [];
        $condition [] = ['id', '=', $param['channel_id']];
        $rule = WaChannel::find($condition);
        return IndexController::successed($rule, '渠道信息');
    }

}